package com.zzx.boot.utils;

import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.function.Function;

/**
 * @author tan
 * @version 1.0
 * @date 2023/7/8 21:02
 */
@Component
public class Transaction {

    @Resource
    private PlatformTransactionManager manager;

    /**
     * 开启事务
     * @param supplier
     * @param <T>
     * @return
     */
    public  <T>T submit(Supplier<T> supplier){
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transaction = manager.getTransaction(definition);

        try{
            T t = supplier.get();
            manager.commit(transaction);
            return t;
        }catch (Exception e){
            // 回滚
            manager.rollback(transaction);
            e.printStackTrace();
            throw e;
        }
    }

}
